package br.com.foxline.atlasmobile.novocadastro;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import br.com.foxline.atlasmobile.CreateMainActivity;
import br.com.foxline.atlasmobile.MenuActivity;
import br.com.foxline.atlasmobile.R;
import br.com.foxline.atlasmobile.dao.BairroDao;
import br.com.foxline.atlasmobile.dao.CityDao;
import br.com.foxline.atlasmobile.dao.DneDao;
import br.com.foxline.atlasmobile.dao.EnderecoDao;
import br.com.foxline.atlasmobile.entities.Dne;
import br.com.foxline.atlasmobile.entities.Endereco;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.enums.Caracterizacao;
import br.com.foxline.atlasmobile.enums.Comando;
import br.com.foxline.atlasmobile.enums.SituacaoImovel;
import br.com.foxline.atlasmobile.util.UtilConnection;

@SuppressLint("NewApi")
public class DadosGeraisActivity extends Fragment {

	private Context context;
	private View view;


	// DAO
	private EnderecoDao enderecoDao;
	private BairroDao bairroDao;
	private DneDao dneDao;

	private Spinner comandoSpinner;
	private Spinner caracterizacaoImovel;
	private EditText inscd;
	private EditText inscs;
	private EditText inscQuadra;
	private EditText inscLote;
	private EditText inscUnid;
	private EditText cep;
	private EditText logradouro;
	private EditText numero;
	private EditText comple;
	private Spinner bairro;

	private Imovel imovel;
	private Endereco endereco;

	private List<String> bairros;

	private AlertDialog dialog;

	private Button next;
	private Button previous;
	

	private TextWatcher keyChangeFocus(final int qtd, final EditText nextEdit) {
		return new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence value, int arg1, int arg2,
					int arg3) {

				if (value != null && value.length() == qtd) {
					nextEdit.requestFocus();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		};
	}

	private void loadFields() {
		inscd = (EditText) view.findViewById(R.id.insc_d);
		inscs = (EditText) view.findViewById(R.id.insc_s);
		inscQuadra = (EditText) view.findViewById(R.id.insc_quadra);
		inscLote = (EditText) view.findViewById(R.id.lote);
		inscUnid = (EditText) view.findViewById(R.id.insc_unid);
		cep = (EditText) view.findViewById(R.id.cep);
		comandoSpinner = (Spinner) view.findViewById(R.id.comando_spinner);
		caracterizacaoImovel = (Spinner) view.findViewById(R.id.caracterizacao_imovel);
		logradouro = (EditText) view.findViewById(R.id.logradouro);
		numero = (EditText) view.findViewById(R.id.num);
		comple = (EditText) view.findViewById(R.id.compl);
		bairro = (Spinner) view.findViewById(R.id.nome_bairro);

		next = (Button) view.findViewById(R.id.next);
		previous = (Button) view.findViewById(R.id.previous);

		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				next();
			}
		});

		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				previous();
			}
		});

		

	}

	private void setKeyChange() {
		inscd.addTextChangedListener(keyChangeFocus(2, inscs));

		inscs.addTextChangedListener(keyChangeFocus(2, inscQuadra));

		inscQuadra.addTextChangedListener(keyChangeFocus(3, inscLote));

		inscLote.addTextChangedListener(keyChangeFocus(4, inscUnid));

		inscUnid.addTextChangedListener(keyChangeFocus(2, cep));

		cep.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence value, int arg1, int arg2,
					int arg3) {

				if (value != null && value.length() == 8) {
					searchDne(String.valueOf(value));
				} else {
					logradouro.setEnabled(true);
					bairro.setEnabled(true);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
	}

	private void loadDao() {
		dneDao = new DneDao(context);
		bairroDao = new BairroDao(context);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater
				.inflate(R.layout.activity_dados_gerais, container, false);

		view = rootView;
		context = container.getContext();

		loadFields();
		loadDao();


		
		bairros = bairroDao
				.getBairros(new CityDao(context).getCity("Parnaíba"));

		bairro.setAdapter(new ArrayAdapter<String>(context,
				R.layout.spinner_item, bairros));

		ArrayAdapter<Comando> comandoArray = new ArrayAdapter<Comando>(
				getActivity().getApplicationContext(), R.layout.spinner_item,
				Comando.values());

		ArrayAdapter<Caracterizacao> caracterizacaoArray = new ArrayAdapter<Caracterizacao>(
				getActivity().getApplicationContext(), R.layout.spinner_item,
				Caracterizacao.values());
		
		comandoSpinner.setAdapter(comandoArray);
		caracterizacaoImovel.setAdapter(caracterizacaoArray);

		//imovel = new Imovel();
		imovel = ((CriarImovelActivity) getActivity()).getImovel();
		
		
		if (imovel.getId() != null) {
			
			loadFields();

			//CARREGA SPINNERS
			comandoSpinner.setSelection(Arrays.asList(Comando.values())
					.indexOf(imovel.getComando()));

			inscd.setText(convert(imovel.getInscricaoCadastralD()));
			inscs.setText(convert(imovel.getInscricaoCadastralS()));
			inscQuadra.setText(convert(imovel.getInscricaoCadastralQuadra()));
			inscLote.setText(convert(imovel.getInscricaoCadastralLote()));
			inscUnid.setText(convert(imovel.getInscricaoCadastralUnid()));

			if (imovel.getEnderecoImovel() != null) {
				endereco = imovel.getEnderecoImovel();
				cep.setText(endereco.getCep());
				logradouro.setText(endereco.getLogradouro());
				numero.setText(valueOf(endereco.getNumero()));
				comple.setText(endereco.getCompl());
				bairro.setSelection(bairros.indexOf(endereco.getBairro()));

			} else {
				endereco = new Endereco();
			}

		} 
		
		setKeyChange();
		
		return rootView;
	}

	public String convert(Integer i) {
		return i == null ? "" : i + "";
	}

	public void save() {
		imovel.setComando((Comando) comandoSpinner.getSelectedItem());
		
		imovel.setInscricaoCadastralD(parseInt(inscd.getText().toString()));
		imovel.setInscricaoCadastralS(parseInt(inscs.getText().toString()));
		imovel.setInscricaoCadastralQuadra(parseInt(inscQuadra.getText()
				.toString()));
		imovel.setInscricaoCadastralLote(parseInt(inscLote.getText().toString()));
		imovel.setInscricaoCadastralUnid(parseInt(inscUnid.getText().toString()));

		saveEndereco();
		salvarImovel();
		
	}

	public void saveEndereco() {
		enderecoDao = new EnderecoDao(context);
		endereco.setCep(cep.getText().toString());
		endereco.setLogradouro(logradouro.getText().toString());
		endereco.setNumero(parseInt(numero.getText().toString()));
		endereco.setCompl(comple.getText().toString());
		endereco.setBairro((String) bairro.getSelectedItem());

		if (endereco.getId() == null) {
			enderecoDao.create(endereco);
		} else {
			enderecoDao.update(endereco);
		}

		imovel.setEnderecoImovel(endereco);

	}
	
	public void salvarImovel(){
		((CriarImovelActivity) getActivity()).salvarImovel();
	}

	public Integer parseInt(String str) {
		try {
			return (Integer.parseInt(str));
		} catch (Exception e) {
			return null;
		}

	}

	public void next() {
		if(inscs.getText().toString() == null || inscs.getText().toString().isEmpty() ){
			Toast.makeText(context, "Campo Setor deve ser preenchido.", Toast.LENGTH_SHORT).show();
			inscs.setError("Campo obrigatório");
			return;
		}
		if(inscQuadra.getText().toString() == null || inscQuadra.getText().toString().isEmpty() ){
			Toast.makeText(context, "Campo quadra deve ser preenchido.", Toast.LENGTH_SHORT).show();
			inscQuadra.setError("Campo obrigatório");
			return;
		}
		save();
		
		//NEXT
		
		((CriarImovelActivity) getActivity()).displayView(1);
	}

	public void previous() {
		// NOTHING
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getActivity().getMenuInflater().inflate(R.menu.create_main, menu);
	// return true;
	// }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.finalizar:
			dialogSituacao();
			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void exibeMensagem(String msg) {
		Toast.makeText(getActivity().getApplicationContext(), msg,
				Toast.LENGTH_SHORT).show();
	}

	public void dialogSituacao() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("Situação do Imóvel");

		final String[] items = new String[SituacaoImovel.values().length];
		int cont = 0;
		final Map<Integer, SituacaoImovel> map = new HashMap<Integer, SituacaoImovel>();

		for (SituacaoImovel si : SituacaoImovel.values()) {
			items[cont] = si.toString();
			map.put(cont, si);
			cont++;
		}

		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				imovel.setSituacaoImovel(map.get(which));
				save();
				imovel.getSituacaoImovel();
				finalCadastro();
			}
		});

		AlertDialog dsituacao = builder.create();
		dsituacao.show();
	}

	public void finalCadastro() {

		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

		builder.setNeutralButton("Finalizar e usar como modelo",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getActivity()
								.getApplicationContext(),
								CreateMainActivity.class);

						imovel.setId(null);

						if (imovel.getEnderecoImovel() != null)
							imovel.getEnderecoImovel().setId(null);
						if (imovel.getEnderecoCorrespondencia() != null)
							imovel.getEnderecoCorrespondencia().setId(null);
						if (imovel.getAnnex() != null) {
							imovel.setAnnex(null);
						}
						if (imovel.getDimensoes() != null) {
							imovel.getDimensoes().setId(null);
						}
						if (imovel.getProprietarios() != null) {
							for (Proprietario p : imovel.getProprietarios()) {
								p.setId(null);
							}
						}

						intent.putExtra(UtilConnection.IMOVEL, imovel);

						startActivity(intent);
						getActivity().finish();

					}
				});

		builder.setPositiveButton("Finalizar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getActivity()
								.getApplicationContext(), MenuActivity.class);
						startActivity(intent);
						getActivity().finish();

					}
				});

		builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		builder.setMessage("Desejar finalizar o cadastro").setTitle(
				"Cadastro Finalizado");

		dialog = builder.create();
		dialog.show();
	}

	

	private void searchDne(String cep) {
		Dne dne = dneDao.getDne(cep);

		if (dne != null) {
			dne.setBairro(bairroDao.find(dne.getBairro().getId()));
			this.logradouro.setText(dne.getNomeclog());
			this.bairro
					.setSelection(bairros.indexOf(dne.getBairro().getNome()));

			this.logradouro.setEnabled(false);
			this.bairro.setEnabled(false);
			this.numero.requestFocus();
		} else {
			Toast.makeText(context, "Endereço não encontrado !",
					Toast.LENGTH_SHORT).show();
			this.logradouro.setEnabled(true);
			this.bairro.setEnabled(true);
		}
	}

	public String valueOf(Integer x) {
		if (x != null) {
			return String.valueOf(x);
		}
		return "";
	}
}
